import 'dart:convert';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:h_flutter_119/api/Api.dart';
import 'package:h_flutter_119/http/httpUtils.dart';
import 'package:h_flutter_119/page/home/model/home_eye_entity.dart';
import 'package:h_flutter_119/page/home/widget/ItemHomeWidget.dart';
import 'package:keframe/keframe.dart';
import '../../utils/log_utils.dart';
import 'model/home_eye_itemlist_entity.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HomePageState();

  HomePage({Key? key}) : super(key: key);
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin{

  @override
  bool get wantKeepAlive => true;

  List<EyeItemList> items = [];
  String date = "";
  int _page = 1;
  late SwiperController _swipeControol;
  late EasyRefreshController _easyRefreshController;
  late ScrollController _scrollController;
  @override
  void dispose() {
    super.dispose();
    _swipeControol.dispose();
    _easyRefreshController.dispose();
  }

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _easyRefreshController = EasyRefreshController(
        controlFinishRefresh: true, controlFinishLoad: true);
    _swipeControol = SwiperController();
    getHomeData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: Visibility(
        visible: items.length > 20 ,
          child: FloatingActionButton(
            onPressed: () {
              _scrollController.animateTo(0, duration: const Duration(milliseconds: 300), curve: Curves.ease);
            }, child: const Icon(Icons.arrow_upward_rounded),
      )),
      body: EasyRefresh.builder(
        controller: _easyRefreshController,
        header: const PhoenixHeader(

        ),
        footer: const PhoenixFooter(),
        onRefresh: () async {
          await Future.delayed(const Duration(seconds: 1), () {
            if (!mounted) {
              return;
            }
            setState(() {
              _page = 1;
            });
            getHomeData();
            _easyRefreshController.finishRefresh();
            _easyRefreshController.resetFooter();
          });
        },
        onLoad: () async {
          await Future.delayed(const Duration(seconds: 1), () {
            setState(() {
              _page++;
            });
            getHomeData();
            _easyRefreshController.finishLoad(IndicatorResult.success);
          });
        },
        childBuilder: (context, physics) {
          return SizedBox(
            child: SizeCacheWidget(
              child: ListView.builder(
                controller: _scrollController,
                itemBuilder: (context, index) {
                  return ItemHomeWidget(_swipeControol, items[index]);
                },
                physics: physics,
                itemCount: items.length,
              ),
            ),
          );
        },
      ),
    );
  }

  void getHomeData() async {
    if (_page == 1) {
      items.clear();
      date = "";
    }
    var response = await HttpUtils.getInstance()
        .get(Api.HOME_DATA, data: {"date": date, "num": _page});
    var homeDataMap = json.decode(response.toString());
    var entity = HomeEyeEntity.fromJson(homeDataMap);
    var nextPage = entity.nextPageUrl ?? "";
    var split = nextPage.split("?");
    var split2 = split[1];
    var split3 = split2.split("&");
    var split4 = split3[0].split("=");
    date = split4[1];
    LogE("split=$split split2=$split2 split3=$split3 split4=$split4 date=$date");
    setState(() {
      items.addAll(entity.issueList?.first.itemList ?? []);
    });
  }


}
